package com.nanchen.compresshelper;

import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.PixelMap;
import ohos.media.image.ImageSource;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Bitmap 压缩相关操作工具类
 * <p>
 * <p>
 * <p>
 * 原理不明白请查看我博客：http://www.cnblogs.com/liushilin/p/6116759.html
 * <p>
 * Author: nanchen
 * Email: liushilin520@foxmail.com
 * Date: 2017-02-13  15:43
 */
public class ImageUtil {
    private static final String TAG = "MainAbility - Image";

    /**
     * 计算图片的压缩比率
     *
     * @param size      size
     * @param reqWidth  目标的宽度
     * @param reqHeight 目标的高度
     * @return int   计算的SampleSize
     */
    private static int calculateInSampleSize(Size size, int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        int height = size.height;
        int width = size.width;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * 从Resources中加载图片
     *
     * @param context   上下文
     * @param resId     资源id
     * @param reqWidth  请求宽度
     * @param reqHeight 请求高度
     * @param config    pixformat
     * @return PixelMap
     */
    public static PixelMap decodeSampledBitmapFromResource(Context context, int resId, int reqWidth, int reqHeight, PixelFormat config) {
        String path = FileUtil.getPathById(context, resId);
        if (StringUtil.isEmpty(path)) {
            return null;
        }
        ImageSource imageSource = null;
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        try {
            Resource asset = assetManager.openRawFile();
            imageSource = ImageSource.create(asset, options);
        } catch (IOException ex) {
            Logger.getLogger(ImageUtil.class.getName()).log(Level.SEVERE, ex.getMessage());
        }
        if (imageSource == null) {
            return null;
        }
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.sampleSize = calculateInSampleSize(imageSource.getImageInfo().size, reqWidth, reqHeight);
        decodingOpts.desiredPixelFormat = config;
        decodingOpts.desiredSize = new Size(reqWidth, reqHeight);
        PixelMap pixelMap = imageSource.createPixelmap(decodingOpts);
        return pixelMap;
    }

    /**
     * 通过传入的bitmap，进行压缩，得到符合标准的bitmap
     *
     * @param src       Bitmap源图
     * @param dstWidth  宽度
     * @param dstHeight 高度
     * @return PixelMap         新的Bitmap
     */
    private static PixelMap createScaleBitmap(PixelMap src, int dstWidth, int dstHeight) {
        if (src == null) {
            return null;
        }
        // 如果是放大图片，filter决定是否平滑，如果是缩小图片，filter无影响，我们这里是缩小图片，所以直接设置为false
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size = new Size(dstWidth, dstHeight);
        initializationOptions.releaseSource = true;
        PixelMap dst = PixelMap.create(src, initializationOptions);
        if (src != dst) { // 如果没有缩放，那么不回收
            src.release(); // 释放Bitmap的native像素数组
        }
        return dst;
    }

    /**
     * 从SD卡上加载图片
     *
     * @param context   上下文
     * @param pathName  路径
     * @param reqWidth  请求宽度
     * @param reqHeight 请求高度
     * @return Bitmap
     */
    private static PixelMap decodeSampledBitmapFromFile(Context context, String pathName, int reqWidth, int reqHeight) {
        if (StringUtil.isEmpty(pathName)) {
            return null;
        }
        ImageSource imageSource = null;
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(pathName);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        try {
            Resource asset = assetManager.openRawFile();
            imageSource = ImageSource.create(asset, options);
        } catch (IOException ex) {
            Logger.getLogger(ImageUtil.class.getName()).log(Level.SEVERE, ex.getMessage());
        }
        if (imageSource == null) {
            return null;
        }
        return createScaleBitmap(imageSource.createPixelmap(null), reqWidth, reqHeight);
    }

    /**
     * 删除临时图片
     *
     * @param path 图片路径
     */
    public static void deleteTempFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            boolean isDelete = file.delete();
        }
    }
}
